Page({
  onFeeInput(e) {
    let value = e.detail.value; 
    // 过滤非法字符（仅保留数字和一个小数点）
    value = value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace(/^\./, '');
    this.setData({
      feeValue: value,
      amount: value ? Number(value) : 0
    });
  },

  onCodeInput(e) {
    const index = e.currentTarget.dataset.index;
    const value = e.detail.value;
    this.setData({
      [`codeList[${index}].code`]: value
    });
  },
  onLoad() {
    if (getCurrentPages().length === 1) {
      // 如果是通过 switchTab 进入，添加自定义返回按钮
      this.setData({ isTabEntry: true });
    }
  },
  backToHome() {
    wx.switchTab({ url: '/pages/index/index' });
  },
  data: {
    // 收货信息
    name: '',
    phone: '',
    address: '',
    
    // 取件码列表
    codeList: [
      {
        code:'',
        selectedExpress:'',
        expressList:['韵达', '圆通', '申通', '顺丰', '极兔', '京东']
      }
    ],
    stopPropagation: function() {
      // 空函数仅用于阻止冒泡
    },
    // 备注
    remark: '',
    
    // 物品重量
    weightValue: '25公斤以内',
    weightOptions: ['25公斤以内', '26-30公斤', '31-40公斤', '41-50公斤'],
    
    // 订单金额
    amount: ''
  },

  // 输入处理
  onNameInput(e) {
    this.setData({ name: e.detail.value });
  },
  
  onPhoneInput(e) {
    this.setData({ phone: e.detail.value });
  },
  onAddressInput(e) {
    this.setData({ address: e.detail.value });
  },
  
  onRemarkInput(e) {
    this.setData({ remark: e.detail.value });
  },
  
  onAmountInput(e) {
    this.setData({ amount: e.detail.value });
  },
  

  // 删除取件码
  onDeleteCode(e) {
    const index = e.currentTarget.dataset.index;
    if (this.data.codeList.length <= 1) return;
    
    const newList = this.data.codeList.filter((_, i) => i !== index);
    this.setData({ codeList: newList });
  },

  // 添加快递码项
  addCodeItem() {
    if (this.data.codeList.length >= 10) {
      wx.showToast({ title: '最多添加10个取件码', icon: 'none' });
      return;
    }
    
    const newItem = {
      code: '',
      selectedExpress: '',
      expressList:['韵达', '圆通', '申通', '顺丰', '极兔', '京东']
    };
    
    this.setData({
      codeList: [...this.data.codeList, newItem]
    });
  },

  noop: function() {}, 
  
  // 修正快递公司选择逻辑
  selectExpress(e) {
    const index = e.currentTarget.dataset.index;
    const express = e.currentTarget.dataset.express;
    
    // 调试日志（重要！）
    console.log('当前选中:', express, '数组位置:', index);
    
    this.setData({
      [`codeList[${index}].selectedExpress`]: express
    }, () => {
      console.log('更新后数据:', this.data.codeList[index]);
    });
  },



  // 显示重量选项
  showWeightOptions() {
    wx.showActionSheet({
      itemList: this.data.weightOptions,
      success: (res) => {
        this.setData({
          weightValue: this.data.weightOptions[res.tapIndex]
        });
      }
    });
  },
  // 提交订单
  submitOrder() {
    const { name, phone, address, codeList, remark, weightValue, amount } = this.data;
    
    // ✅ 新增：验证逻辑（保持不变）
    if (!name || !phone || !address) {
      wx.showToast({ title: '请填写完整收货信息', icon: 'none' });
      return;
    }
    if (codeList.some(item => !item.code)) {
      wx.showToast({ title: '请填写所有取件码', icon: 'none' });
      return;
    }
    if (codeList.some(item => !item.selectedExpress)) {
      wx.showToast({ title: '请为每个取件码选择快递公司', icon: 'none' });
      return;
    }
  
    // ✅ 新增：构建订单数据
    const orderData = {
      id: Date.now(), // 唯一ID
      name,
      phone,
      address,
      codeList: codeList.map(item => ({
        code: item.code,
        express: item.selectedExpress
      })),
      remark,
      weight: weightValue,
      amount: Number(this.data.amount) || 0,
      commit: Number(this.data.amount) || 0,
      status: '进行中', // 初始状态
      createTime: new Date().toLocaleString()
    };
  
    // ✅ 核心修改：存储到本地缓存
    const orders = wx.getStorageSync('orders') || [];
    orders.unshift(orderData);
    wx.setStorageSync('orders', orders);
  
    // ✅ 新增：成功提示和跳转
    wx.showToast({ 
      title: '发布成功', 
      icon: 'success',
      success: () => {
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/orderlist/orderlist'
          });
          // 重置表单
          this.setData({
            name: '',
            phone: '',
            address: '',
            codeList: [{ code: '', selectedExpress: '' }],
            remark: '',
            amount: ''
          });
        }, 1500);
      }
    });
  }
});